//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Web.UI.WebControls;

using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Controls;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace CommunityServer.Blogs.Controls
{
    /// <summary>
    /// Summary description for ThreadedComments.
    /// </summary>
    public class ThreadedComments : WeblogThemedControl, ICommentsView
    {
        private CommentForm form = null;
        private PlaceHolder comments = null;
        private TextBox TestBox = null;
        
        public ThreadedComments()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        private PostSet _dataSource;

        /// <summary>
        /// Property DataSource (object)
        /// </summary>
        public PostSet DataSource
        {
            get
            { return this._dataSource; }
            set
            { this._dataSource = value; }
        }
        [DefaultValue(false)]
        public virtual bool HideOnNoComments
        {
            get
            {
                Object state = ViewState["HideOnNoComments"];
                if (state != null)
                    return (bool)state;
                return false;
            }
            set { ViewState["HideOnNoComments"] = value; }
        }
        protected override void AttachChildControls()
        {
            comments = FindControl("comments") as PlaceHolder;
            form = FindControl("form") as CommentForm;
            TestBox = FindControl("TestBox") as TextBox;
        }
        public override void DataBind()
        {
            this.EnsureChildControls();

            if (comments != null)
            {
                foreach (WeblogPost post in DataSource.Replies)
                {
                    if (post.ParentID == DataSource.ThreadStarter.PostID)
                    {
                        comments.Controls.Add(CreateComment(post));
                    }
                    else
                    {
                        Control control = FindControlRecursive(comments, post.ParentID.ToString());
                        if (control != null) control.Controls.Add(CreateReply(post));
                    }
                }
            }

            form.DataSource = (WeblogPost) DataSource.ThreadStarter;
            form.DataBind();
        }
        private Control FindControlRecursive(Control root, string id)
        {
            if (root.ID == id)
            {
                return root;
            }

            foreach (Control c in root.Controls)
            {
                Control t = FindControlRecursive(c, id);
                if (t != null)
                {
                    return t;
                }
            }

            return null;
        }
        private HtmlGenericControl CreateReply(WeblogPost post)
        {
            HtmlGenericControl reply = new HtmlGenericControl("div");
            reply.Attributes.Add("class", "reply");
            reply.ID = post.PostID.ToString();

            HyperLink replyLink = new HyperLink();
            reply.Controls.Add(replyLink);
            replyLink.Text = post.Subject;
            replyLink.NavigateUrl = "javascript:void(0);";
            replyLink.Attributes.Add("onclick", "showReply(this)");

            HtmlGenericControl replyBy = new HtmlGenericControl("span");
            reply.Controls.Add(replyBy);
            replyBy.Attributes.Add("class", "replyTitle");
            replyBy.InnerText = " | by " + post.Username;

            HtmlGenericControl replyTime = new HtmlGenericControl("span");
            reply.Controls.Add(replyTime);
            replyTime.InnerText = post.PostDate.ToString(" on ddd dd MMMM yyyy HH:mm");
            
            HtmlGenericControl replyCommands = new HtmlGenericControl("span");
            reply.Controls.Add(replyCommands);
            replyCommands.InnerText = " | ";
            CreateReplyLink(replyCommands, post);

            HtmlGenericControl replyBody = new HtmlGenericControl("div");
            reply.Controls.Add(replyBody);
            replyBody.Attributes.Add("class", "replyBody hide");
            replyBody.InnerHtml = post.FormattedBody;

            return reply;
        }
        private HtmlGenericControl CreateComment(WeblogPost post)
        {
            // This is the outer div
            HtmlGenericControl commentArea = new HtmlGenericControl("div");
            commentArea.ID = "CommentArea_" + post.PostID.ToString();
            commentArea.Attributes.Add("class", "CommentArea");

            // Create the main comment
            HtmlGenericControl comment = new HtmlGenericControl("div");
            commentArea.Controls.Add(comment);
            comment.ID = post.PostID.ToString();
            comment.Attributes.Add("class", "TopLevelComment");

            // Create the header
            HtmlGenericControl header = new HtmlGenericControl("h4");
            comment.Controls.Add(header);
            header.ID = "CommentTitle_" + post.PostID.ToString();
            header.Attributes.Add("class", "CommentTitle");
            header.InnerText = post.Username + " says:";

            // Create the bubble arrow
            Image bubbleImage = new Image();
            header.Controls.Add(bubbleImage);
            bubbleImage.ID = "CommentImage_" + post.PostID.ToString();
            bubbleImage.CssClass = "CommentArrow";
            bubbleImage.ImageUrl = Globals.GetSkinPath() + "/images/spacer.gif";
            bubbleImage.AlternateText = "";

            // And now the date etc.
            HtmlGenericControl postDate = new HtmlGenericControl("span");
            header.Controls.Add(postDate);
            postDate.ID = "CommentDate_" + post.PostID.ToString();
            postDate.Attributes.Add("class", "CommentDate");
            postDate.InnerText = post.PostDate.ToString("on ddd dd MMMM yyyy HH:mm");

            // Create the reply link
            HtmlGenericControl commentCommands = new HtmlGenericControl("span");
            header.Controls.Add(commentCommands);
            commentCommands.ID = "CommentCommands_" + post.PostID.ToString();
            commentCommands.Attributes.Add("class", "CommentCommands");

            CreateReplyLink(commentCommands, post);

            // And now the actual comment
            HtmlGenericControl commentText = new HtmlGenericControl("div");
            comment.Controls.Add(commentText);
            commentText.ID = "CommentText" + post.PostID.ToString();
            commentText.Attributes.Add("class", "CommentThreadedText");
            commentText.InnerHtml = post.FormattedBody;

            return commentArea;
        }
        private void CreateReplyLink(Control container, WeblogPost post)
        {
            if (post.Weblog.EnableNewComments((WeblogPost) DataSource.ThreadStarter, CSContext.Current.User))
            {
                LinkButton replyButton = new LinkButton();
                container.Controls.Add(replyButton);
                replyButton.ID = "RepyButton_" + post.PostID.ToString();
                replyButton.Text = "Reply";
                replyButton.CausesValidation = false;
                replyButton.CommandArgument = post.PostID.ToString();
                replyButton.Command += new CommandEventHandler(replyButton_Command);
            }
        }
        void replyButton_Command(object sender, CommandEventArgs e)
        {
            int postId = Convert.ToInt32(e.CommandArgument);

            WeblogPost post = (WeblogPost) DataSource.ThreadStarter;
            string url = BlogUrls.Instance().Post(post, post.Weblog);
            Context.Response.Redirect(string.Format("{0}?Reply={1}#CommonCommentForm", url, e.CommandArgument));            
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureChildControls();

            int replyPost = 0;
            object queryString = Context.Request["Reply"];
            if (queryString != null) replyPost = Convert.ToInt32(queryString);
            
            if (replyPost > 0)
            {
                form.ParentPostId = replyPost;
            }            
        }
    }
}